import { Button, Card, Form, Input, Select, Space, Table } from "antd";
import { SearchOutlined } from "@ant-design/icons";
import { useForm } from "antd/lib/form/Form";
import React, { Key, useEffect, useState } from "react";
import { ColumnsType } from "antd/lib/table";
import { getCitiesOrDistrict, getHosTypes, getHospitalList, getProvinces } from "@/api/hospital/hospitalList";
import { DictItems, HospitalListItem, HospitalListItems, HospitalSearchForm } from "@/api/hospital/hospitalList/types";
import { Link, useNavigate } from "react-router-dom";
//获得 Option 组件
const { Option } = Select;

export default function HospitalList() {
  const navigate = useNavigate()

  // 声明省份信息的状态
  let [provinces, setProvinces] = useState<DictItems>([]);
  // 声明城市信息的状态
  let [cities, setCities] = useState<DictItems>([]);
  // 声明区县信息的状态
  let [district, setDistrict] = useState<DictItems>([]);
  //声明医院类型的状态
  let [types, setType] = useState<DictItems>([]);
  //声明医院列表数据的状态
  let [hospital, setHospital] = useState<HospitalListItems>([]);
  //声明与分页相关的状态
  let [total, setTotal] = useState(0);
  let [pageSize, setPageSize] = useState(5);
  let [current, setCurrent] = useState(1);
  //loading 功能的状态
  let [loading, setLoading] = useState(false);
  //声明一个表单元素值的状态
  let [values, setValues] = useState<HospitalSearchForm>({});

  //声明事件回调
  let onFinish = (values: HospitalSearchForm) => {
    //发送 AJAX 请求
    setValues(values);
  };
  let clear = () => {};
  let [form] = useForm();

  //定义表格结构
  let columns: ColumnsType<HospitalListItem> = [
    {
      title: "序号",
      render: (value, record, index) => {
        return index + 1;
      },
    },
    {
      title: "医院logo",
      dataIndex: "logoData",
      render: (value) => {
        return <img width="70" src={`data:image/png;base64, ${value}`} />;
      },
    },
    {
      title: "医院名称",
      dataIndex: "hosname",
    },
    {
      title: "等级",
      render: (value, record) => {
        return record.param.hostypeString;
      },
    },
    {
      title: "详细地址",
      render: (value, record) => {
        return record.param.fullAddress;
      },
    },
    {
      title: "状态",
      dataIndex: "status",
      render: (value, record) => {
        // return record.status ? '已上线' : '未上线'
        return value ? "已上线" : "未上线";
      },
    },
    {
      title: "创建时间",
      dataIndex: "createTime",
      render: (value) => {
        return value;
      },
    },
    {
      title: "操作",
      render: (value, record) => {
        return (
          <Space>
            <Link to={`/syt/hospital/hospitalList/show/${record.id}`}><Button type="primary">查看</Button></Link>
            <Button type="primary" onClick={() => navigate(`/syt/hospital/hospitalList/schedule/${record.hoscode}`)}>排班</Button>
            <Button type="primary">下线</Button>
          </Space>
        );
      },
    },
  ];

  //useEffect
  useEffect(() => {
    //声明函数
    let getProvince = async () => {
      //发送请求获取省份信息
      let provinces = await getProvinces();
      //更新省份信息的状态
      setProvinces(provinces);
    };
    getProvince();

    //获取医院类型
    let getTypes = async () => {
      let types = await getHosTypes();
      setType(types);
    }
    getTypes();
  }, []);

  //获取医院数据
  useEffect(() => {
    let getHospital = async () => {
      setLoading(true);
      //发送请求获取医院数据
      let result = await getHospitalList({
        page: current,
        limit: pageSize,
        ...values
      });
      //更新状态
      setHospital(result.content);
      //更新总数
      setTotal(result.totalElements);
      //更新 loading 的状态
      setLoading(false);
    }
    getHospital();
  }, [current, pageSize, values]);

  //事件回调
  let getCities = async (value: Key) => {
    //设置城市下拉框的值为空
    form.setFieldsValue({
      cityCode: undefined,
      districtCode: undefined
    });
    //清空城市列表
    setCities([]);
    setDistrict([]);
    //获取城市的信息
    let result = await getCitiesOrDistrict(value);
    //更新城市列表的状态
    setCities(result);
  };

  //获取区县的列表
  let getDistrict = async (value: Key) => {
    //清空区县下拉框的值
    form.setFieldsValue({
      districtCode: undefined
    });
    //清空城市列表的值
    setDistrict([]);
    //发送请求
    let district = await getCitiesOrDistrict(value);
    //渲染
    setDistrict(district);
  };

  return (
    <Card>
      {/* 表单部分 */}
      <Form
        form={form}
        name="hospital-list"
        onFinish={onFinish}
        autoComplete="off"
        layout="inline"
      >
        <Form.Item name="provinceCode">
          <Select placeholder="请选择省" onChange={getCities} allowClear>
            {provinces.map((item) => {
              return (
                <Option key={item.id} value={item.value}>
                  {item.name}
                </Option>
              );
            })}
          </Select>
        </Form.Item>

        <Form.Item name="cityCode">
          <Select placeholder="请选择市" onChange={getDistrict} allowClear>
            {cities.map((item) => {
              return (
                <Option key={item.id} value={item.value}>
                  {item.name}
                </Option>
              );
            })}
          </Select>
        </Form.Item>

        <Form.Item name="districtCode">
          <Select placeholder="请选择区" onChange={() => {}} allowClear>
            {district.map((item) => {
              return (
                <Option key={item.id} value={item.value}>
                  {item.name}
                </Option>
              );
            })}
          </Select>
        </Form.Item>
        <Form.Item name="hosname">
          <Input placeholder="医院名称" />
        </Form.Item>

        <Form.Item name="hoscode">
          <Input placeholder="医院编号" />
        </Form.Item>
        <Form.Item name="hostype">
          <Select placeholder="医院类型" onChange={() => {}} allowClear>
            {
              types.map((item) => {
                return (
                  <Option key={item.id} value={item.value}>
                    {item.name}
                  </Option>
                );
              })
            }
          </Select>
        </Form.Item>
        <Form.Item name="status">
          <Select placeholder="医院状态" onChange={() => {}} allowClear>
            <Option value="0">未上线</Option>
            <Option value="1">已上线</Option>
          </Select>
        </Form.Item>
        <Form.Item>
          <Space>
            <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
              查询
            </Button>
            <Button onClick={clear}>清空</Button>
          </Space>
        </Form.Item>
      </Form>

      {/* 表格部分 */}
      <Table 
        loading={loading}
        columns={columns} 
        dataSource={hospital} 
        bordered 
        rowKey={"id"}
        pagination={{
          total,
          pageSize,
          current,
          showSizeChanger: true,
          pageSizeOptions: [5,10,15,20],
          showTotal: total => {
            return `总计: ${total} 条数据`
          },
          onChange: (page: number, pageSize: number) => {
            //更新状态
            setCurrent(page);
            setPageSize(pageSize);
          }
        }}
        />
    </Card>
  );
}
